package cq.zhcqk.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.dou361.dialogui.DialogUIUtils;
import com.dou361.dialogui.bean.BuildBean;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.tencent.smtt.sdk.WebView;

import org.apache.http.Header;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import cq.zhcqk.R;
import cq.zhcqk.adapter.GridviewAdapter;
import cq.zhcqk.alipay.PayResult;
import cq.zhcqk.app;
import cq.zhcqk.util.AsyncHttpClientUtils;
import cq.zhcqk.util.Common;
import cq.zhcqk.util.GsonUtil;
import cq.zhcqk.util.StringUtil;
import cq.zhcqk.util.WebViewHeader;
import cq.zhcqk.util.wxapi.Constants;
import cq.zhcqk.util.x5.X5WebView;

/**
 * Created by zhangle on 2018/2/27.
 */
public class AxyzDetailActivity  extends AppCompatActivity implements View.OnClickListener{
    private String cid;
    private X5WebView tc_webview;
    private Button juankuan;
    private Activity mActivity;
    private Context context;
    protected BuildBean buildBean;
    private Dialog dialog;
    private AsyncHttpClient httpClient;
    private IWXAPI api;
    private static final int SDK_PAY_FLAG = 1;
    //支付方式1；支付宝，2：微信
    private int payType = 1;

    private ImageView zfbImg;
    private ImageView wxImg;
    private EditText amount;
    private LinearLayout juankuan_lay;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_axyz_detail);
        httpClient = AsyncHttpClientUtils.getInstance().getAsyncHttpClient();
        mActivity = AxyzDetailActivity.this;
        context = this;
        api = WXAPIFactory.createWXAPI(context, null);
        initBack();
        tc_webview = (X5WebView) findViewById(R.id.tc_webview);
        juankuan = (Button) findViewById(R.id.juankuan);
        juankuan_lay = (LinearLayout) findViewById(R.id.juankuan_lay);
        juankuan.setOnClickListener(this);
        initData();
    }

    protected void initData() {
        buildBean = DialogUIUtils.showLoading(this, "加载中...", true, true, true, false);
        cid = getIntent().getStringExtra("cid");
        initInfo(cid);
    }

    @Override
    protected void onResume() {
        super.onResume();
        WebViewHeader.setHeaderAndLoadX5(tc_webview, Common.URL+Common.DICDONATIONDETAIL+"?cid="+cid);
        show();
    }

    private void initBack(){
        ImageView back = (ImageView) findViewById(R.id.header_back);
        TextView title = (TextView) findViewById(R.id.header_text);
        title.setText("和美磁器口");
        back.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.header_back:
                finish();
                break;
            case R.id.juankuan:
                if(!app.isLogin){
                    Toast.makeText(context,"请先登录",Toast.LENGTH_SHORT).show();
                    context.startActivity(new Intent(context, LoginActivity.class));
                    overridePendingTransition(R.anim.in_from_right, R.anim.out_to_left);
                    return;
                }
//                View rootView = View.inflate(mActivity, R.layout.custom_dialog_axyz, null);
                LayoutInflater layoutInflater = LayoutInflater.from(context);
                View rootView = layoutInflater.inflate(R.layout.custom_dialog_axyz, null);
                zfbImg = (ImageView) rootView.findViewById(R.id.zfbImg);
                wxImg = (ImageView) rootView.findViewById(R.id.wxImg);
                amount = (EditText) rootView.findViewById(R.id.amount);
                dialog = DialogUIUtils.showCustomAlert(context, rootView, Gravity.CENTER, true, false).show();
                rootView.findViewById(R.id.ok).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        getOrderInfo(payType);
                    }
                });
                rootView.findViewById(R.id.cancel).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        DialogUIUtils.dismiss(dialog);
                    }
                });
                rootView.findViewById(R.id.zhifb).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        payType = 1;
                        setPayImg(payType);
                    }
                });
                rootView.findViewById(R.id.wxpay).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        payType = 2;
                        setPayImg(payType);
                    }
                });
                break;
        }
    }

    private void initInfo(String cid){
        RequestParams params = new RequestParams();
        params.add("cid",cid);
        String url = "";
        url = Common.URL+Common.CANDO;
        buildBean.show();
        httpClient.post(url,params,new JsonHttpResponseHandler(){
            @Override
            public void onSuccess(int statusCode, Header[] headers,
                                  JSONObject response) {
                super.onSuccess(statusCode, headers, response);
                System.out.println("onSuccess："+response);
                Map<String, Object> map = GsonUtil.GsonToMaps(response+"");
                if(StringUtil.stringToInt(map.get("code")+"") != 0){
//                    Toast.makeText(context,"获取支付信息失败，请稍后再试",Toast.LENGTH_SHORT).show();
                    return;
                }
                if("true".equals(map.get("data")+"")){
                    juankuan_lay.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers,
                                  Throwable throwable, JSONObject errorResponse) {
                super.onFailure(statusCode, headers, throwable,
                        errorResponse);
                System.out.println("errorResponse："+errorResponse);
                Toast.makeText(context,"获取失败，请稍后再试",Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                super.onFailure(statusCode, headers, responseString, throwable);
                System.out.println("responseString："+responseString);
                Toast.makeText(context,"获取失败，请稍后再试",Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFinish() {
                super.onFinish();
                DialogUIUtils.dismiss(buildBean);
            }
        });
    }

    private void setPayImg(int type){
        if(type == 1){
            wxImg.setImageResource(R.mipmap.check_off);
            zfbImg.setImageResource(R.mipmap.check_on);
        }else if(type == 2){
            wxImg.setImageResource(R.mipmap.check_on);
            zfbImg.setImageResource(R.mipmap.check_off);
        }
    }

    public void show(){
        if(tc_webview != null)
        {
            tc_webview.setWebViewClient(new com.tencent.smtt.sdk.WebViewClient()
            {
                @Override
                public void onPageFinished(com.tencent.smtt.sdk.WebView webView, String s) {
                    super.onPageFinished(webView, s);
                    DialogUIUtils.dismiss(buildBean);
                }

                @Override
                public void onPageStarted(com.tencent.smtt.sdk.WebView webView, String s, Bitmap bitmap) {
                    super.onPageStarted(webView, s, bitmap);
                    buildBean.show();
                }

                @Override
                public void onReceivedError(WebView webView, int i, String s, String s1) {
                    super.onReceivedError(webView, i, s, s1);
                    DialogUIUtils.dismiss(buildBean);
                }
            });
        }
    }

    private void getOrderInfo(final int payType){
        int price = 0 ;
        try {
            price = Integer.valueOf(amount.getText().toString());
        }catch (Exception e){
            Toast.makeText(context,"金额格式错误",Toast.LENGTH_SHORT).show();
        }
        if(price == 0){
            Toast.makeText(context,"请输入捐款金额",Toast.LENGTH_SHORT).show();
            return;
        }
        RequestParams params = new RequestParams();
        params.add("dataid",cid);
        params.add("money",price+"");
        params.add("payType",payType+"");
        System.out.println(params);
        String url = "";
        url = Common.URL+Common.DICDONATION;
        buildBean.show();
        httpClient.post(url,params,new JsonHttpResponseHandler(){
            @Override
            public void onSuccess(int statusCode, Header[] headers,
                                  JSONObject response) {
                super.onSuccess(statusCode, headers, response);
                System.out.println("onSuccess："+response);
                Map<String, Object> map = GsonUtil.GsonToMaps(response+"");
                if(StringUtil.stringToInt(map.get("code")+"") != 0){
                    Toast.makeText(context,"获取支付信息失败，请稍后再试",Toast.LENGTH_SHORT).show();
                    return;
                }
                if(map.get("data") == null || "".equals(map.get("data")+"")){
                    Toast.makeText(context,"支付失败，请稍后再试",Toast.LENGTH_SHORT).show();
                }else{
                    DialogUIUtils.dismiss(dialog);
                    if(payType == 1){
                        payV2(map.get("data")+"");
                    }else if(payType == 2){
                        wxPay((Map<String, Object>)map.get("data"));
                    }
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers,
                                  Throwable throwable, JSONObject errorResponse) {
                super.onFailure(statusCode, headers, throwable,
                        errorResponse);
                System.out.println("errorResponse："+errorResponse);
                Toast.makeText(context,"获取失败，请稍后再试",Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                super.onFailure(statusCode, headers, responseString, throwable);
                System.out.println("responseString："+responseString);
                Toast.makeText(context,"获取失败，请稍后再试",Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFinish() {
                super.onFinish();
                DialogUIUtils.dismiss(buildBean);
            }
        });
    }

    /**
     * 发起支付宝支付
     * @param orderInfo
     */
    public void payV2(final String orderInfo) {
        if (StringUtil.isNull(orderInfo)){
            Toast.makeText(context, "获取订单数据失败", Toast.LENGTH_SHORT).show();
            return;
        }

        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                PayTask alipay = new PayTask(mActivity);
                Map<String, String> result = alipay.payV2(orderInfo, true);
                Log.i("msp", result.toString());

                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        Toast.makeText(context, "支付成功", Toast.LENGTH_SHORT).show();
//                        DialogUIUtils.dismiss(dialog);
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        Toast.makeText(context, "支付失败", Toast.LENGTH_SHORT).show();
                    }
                    break;
                }
                default:
                    break;
            }
        }
    };

    /**
     * 微信支付
     * @param orderInfo
     */
    private void wxPay(Map<String, Object> orderInfo){
        PayReq req = new PayReq();
//        req.appId			= orderInfo.get("appid")+"";
        req.appId			= Constants.APP_ID;
        req.partnerId		= orderInfo.get("partnerid")+"";
        req.prepayId		= orderInfo.get("prepayid")+"";
        req.nonceStr		= orderInfo.get("noncestr")+"";
        req.timeStamp		= StringUtil.stringToInt(orderInfo.get("timestamp")+"")+"";
        req.packageValue	= orderInfo.get("package")+"";
        req.sign			= orderInfo.get("sign")+"";
        // 将该app注册到微信
        api.registerApp(Constants.APP_ID);
//        IWXMsg.registerApp;
        api.sendReq(req);
    }

    @Override
    public void finish() {
        super.finish();
        overridePendingTransition(R.anim.slide_left_in, R.anim.slide_right_out);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (this.tc_webview != null) {
            tc_webview.setVisibility(View.GONE);
            tc_webview.removeAllViews();
            tc_webview.destroy();
        }
    }
}
